<template>
  <uni-table 
    border 
    stripe 
    class="optimized-table"
    :data="groupedData"
  >
    <!-- 自定义标题行 -->
    <uni-tr class="custom-header-row"  v-if="tableTitle" >
      <uni-th 
        :colspan="mergedHeaders.length" 
        align="center"
      >
        {{ tableTitle }}
      </uni-th>
    </uni-tr>

    <!-- 动态表头 -->
    <uni-tr>
      <uni-th 
        v-for="(header, index) in mergedHeaders" 
        :key="index"
        width="70" 
        align="center" 
        class="header-cell"
      >
        {{ header.label }}
      </uni-th>
    </uni-tr>

    <!-- 分组数据行 -->
    <uni-tr v-for="(group, groupIndex) in groupedData" :key="groupIndex">
      <template v-for="item in group">
        <uni-td 
          v-for="(header, idx) in headers" 
          :key="idx"
          class="body-cell"
        >
          {{ item ? item[header.prop] : '' }}
        </uni-td>
      </template>
    </uni-tr>
  </uni-table>
</template>

<script>
export default {
  props: {
    tableTitle: {
      type: String,
      default: ''
    },
    headers: {
      type: Array,
      required: true
    },
    tableData: {
      type: Array,
      default: () => []
    },
    groupSize: {
      type: Number,
      default: 1
    }
  },
  computed: {
    // 合并表头（根据分组数重复表头）
    mergedHeaders() {
      return Array.from(
        { length: Math.max(1, this.groupSize) }, 
        () => this.headers
      ).flat()
    },
    // 分组数据（自动填充空数据保证列对齐）
    groupedData() {
      const chunkSize = Math.max(1, this.groupSize)
      const groups = this.tableData.reduce((acc, item, index) => {
        const chunkIndex = Math.floor(index / chunkSize)
        acc[chunkIndex] = acc[chunkIndex] || []
        acc[chunkIndex].push(item)
        return acc
      }, [])

      return groups.map(group => 
        [...group, ...Array(chunkSize - group.length).fill(null)]
      )
    }
  }
}
</script>

<style scoped>
/* 原有样式保持不变 */
.custom-header-row ::v-deep .uni-table-th {
  background-color: #f5f7fa;
  font-weight: bold;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
}

.optimized-table ::v-deep .uni-table-th,
.optimized-table ::v-deep .uni-table-td {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.optimized-table ::v-deep .uni-table-tr {
  display: flex;
  flex-wrap: nowrap;
}

.optimized-table ::v-deep .uni-table-th,
.optimized-table ::v-deep .uni-table-td {
  flex: 1;
  min-width: 100px;
  padding: 12px 8px;
}

.optimized-table {
  font-size: 14px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}

.header-cell {
  background-color: #f5f7fa !important;
  color: #303133;
  font-weight: 600;
}

.body-cell {
  color: #606266;
  line-height: 1.5;
}
</style>